package com.zhanghe.study.xml_parsing.dom.util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zh
 * @date 2020/12/29 16:44
 */
public class SaxUtils {

    /**
     * 生成默认的解析器
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public static SAXParser createDefaultParser(InputStream stream,DefaultHandler handler) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser =  factory.newSAXParser();
        parser.parse(stream,handler);
        return parser;

    }

    public static void readMapper(String fileName){
        InputStream stream = ClassLoader.getSystemResourceAsStream("test.xml");
        SAXParser parser = null;


        try {
            parser = createDefaultParser(stream,new DefaultHandler(){
                // 当前元素
                private String currentTag;
                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

                    System.out.println("开始处理元素"+qName);
                    currentTag = qName;

                    int length = attributes.getLength();
                    if(length > 0){
                        System.out.println(currentTag+"元素中包含属性");
                        for(int i = 0;i<length;i++){
                            System.out.println(attributes.getQName(i)+"--->"+attributes.getValue(i));
                        }
                    }

                }

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    String content = new String(ch,start,length);

                    if(content.trim().length() > 0){
                        System.out.println(currentTag+"元素中的值是"+content);
                    }
                }

                @Override
                public void endDocument() throws SAXException {
                    System.out.println("xml解析完毕");
                }

                @Override
                public void startDocument() throws SAXException {
                    System.out.println("开始读取xml文档");
                }


            });
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new RuntimeException("SAX解析器构建失败",e);
        }
    }

    public static void main(String[] args) {
        readMapper("test.xml");

    }
}
